import json
import sys
import os
import logging
import logging.handlers
import Core.MongoDB as MongoDB
import Core.MySQLDB as MySQLDB
# import Core.Realtimeview as RealTimeView
import Core.JDMySQLDB as JDMySQLDB
import Core.TonghuashunDatabase as THSDatabase
import Core.MAADB as MAADB
import Core.UniDataInterface as UniDB


def CreateFolder(fullPathname):
    existed = os.path.exists(fullPathname)
    if not existed:
        os.makedirs(fullPathname)
        print("Create Folder: " + fullPathname)
    else:
        #print("Folder Existed: " + fullPathname)
        pass


# config_field 文件中需要读取的字段
def create_database(database_type, config_file, config_field=None):
    #
    config_document = json.load(open(config_file, 'r', encoding='utf-8'))
    if config_field:
        config_info = config_document[config_field]
    else:
        config_info = {}
    #
    address = config_info.get("Address")
    port = config_info.get("Port")
    username = config_info.get("Username")
    password = config_info.get("Password")
    dbname = config_info.get("Database")
    #
    database = None

    if database_type == "Mongo":
        pass

    # 标准数据库连接
    elif database_type == "MySQL":
        database = MySQLDB.MySQLDB(address=address, port=port, username=username, password=password)

    # 单库单密码模式
    elif database_type == "JDMySQL":
        databse_config = config_document["Database"]  # 需要传进一组配置信息
        database = JDMySQLDB.JDMySQLDB(address, port, config=databse_config)

    # 兼容同花顺数据库
    elif database_type == "THS":
        database = THSDatabase.THSDatabase(address=address, port=port, username=username, password=password, dbname=dbname)

    # 兼容MAA库
    elif database_type == "MAA":
        database = MAADB.MAADB(address=address, port=port, username=username, password=password, dbname=dbname)

    elif database_type == "Uni":
        database = UniDB.UniDataInterface(config=config_document)

    else:
        print("Config::create_database Unrecognized Database Type", database_type)
        return

    return database


class Config(object):

    __initialized = False
    cfgFile = None
    __loggers__ = {}
    __database = None
    __realtimeViews = {}
    testnum = 0

    def __init__(self, pathFilename=""):
        if not Config.__initialized:
            if pathFilename == "":
                pathFilename = os.getcwd() + "\..\Config\config.json"
            print("Init Config with " + pathFilename)
            Config.cfgFile = json.load(open(pathFilename, 'r', encoding='utf-8'))
            Config.__initialized = True

    def Logger(self, loggerName, consoleOutput=True):
        #
        if loggerName not in Config.__loggers__:
            #
            logger = logging.getLogger(loggerName)
            logger.setLevel(logging.INFO)  # Log等级总开关

            # ---File Name---
            logDir = Config.cfgFile["LogDir"]
            folder = logDir + "\\" + loggerName
            CreateFolder(folder)

            # fh = logging.FileHandler(folder + "\\" + loggerName , mode='a')
            fh = logging.handlers.TimedRotatingFileHandler(folder + "\\" + loggerName, when='D', interval=1, encoding="utf-8")

            # 指定logger输出格式
            formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s: %(message)s')
            fh.setFormatter(formatter)
            logger.addHandler(fh)

            # 往屏幕上输出
            if consoleOutput:
                sh = logging.StreamHandler()  # 往屏幕上输出
                sh.setFormatter(formatter)  # 设置屏幕上显示的格式
                logger.addHandler(sh)

            #
            Config.__loggers__[loggerName] = logger

        return Config.__loggers__[loggerName]

    def DataBase(self, type="MySQL", config_field="Database"):
        #
        config_info = Config.cfgFile[config_field]
        address = config_info.get("Address")
        port = config_info.get("Port")
        username = config_info.get("Username")
        password = config_info.get("Password")
        dbname = config_info.get("Database")

        if Config.__database == None:
            print("Create Database Connection")
            if type == "Mongo":
                addressPort = Config.cfgFile["MongoDBAddressPort"].split(":")
                if Config.cfgFile["MongoDBAuth"] == "Yes":
                    Config.__database = MongoDB.MongoDB(addressPort[0], addressPort[1], Config.cfgFile["MongoDBUsername"], Config.cfgFile["MongoDBPassword"])
                else:
                    Config.__database = MongoDB.MongoDB(addressPort[0], addressPort[1])

            # 标准数据库连接
            elif type == "MySQL":
                Config.__database = MySQLDB.MySQLDB(address=address,
                                                    port=port,
                                                    username=username,
                                                    password=password)
            # 单库单密码模式
            elif type == "JDMySQL":
                databseConfig = Config.cfgFile[config_field]
                Config.__database = JDMySQLDB.JDMySQLDB(address, port, config=databseConfig)

            # 兼容同花顺数据库
            elif type == "THS":
                Config.__database = THSDatabase.THSDatabase(address=address,
                                                            port=port,
                                                            username=username,
                                                            password=password,
                                                            dbname=dbname)
            # 兼容MAA库
            elif type == "MAA":
                Config.__database = MAADB.MAADB(address=address,
                                                port=port,
                                                username=username,
                                                password=password,
                                                dbname=dbname)

            elif type == "Uni":
                Config.__database = UniDB.UniDataInterface(config=Config.cfgFile)

        return Config.__database

    def RealTime(self, db=0):
        #
        if db not in Config.__realtimeViews:
            print("Create RealTimeView Connection")
            config_realtime = Config.cfgFile["Realtime"]
            #
            if "Password" not in config_realtime:
                config_realtime["Password"] = None
            #
            Config.__realtimeViews[db] = RealTimeView.RealTimeView(address=config_realtime["Address"],
                                                                   port=config_realtime["Port"],
                                                                   password=config_realtime["Password"],
                                                                   db=db)
        return Config.__realtimeViews[db]


# ---Instanced Here---
# config = Config()



